<template>
  <div>
    <el-dialog
      v-model="visibleDialog"
      :title="props.title"
      width="1200px"
      draggable
      @close="closeDialog"
    >
      <div class="app-container">
        <div class="search-container">
          <el-form :model="searchParam" :inline="true">
            <!-- <el-form-item label="项目" label-width="70px">
              <el-select
                v-model="searchParam.projectId"
                placeholder="请选择项目"
                clearable
              >
                <el-option
                  v-for="item in projectList"
                  :key="item.id"
                  :label="item.projectName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="工序" label-width="70px">
              <el-select
                v-model="searchParam.processId"
                placeholder="请选择工序"
                clearable
              >
                <el-option
                  v-for="item in processList"
                  :key="item.id"
                  :label="item.processName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="操作类型" label-width="70px">
              <el-select
                v-model="searchParam.opeTypeCode"
                placeholder="请选择操作类型"
                clearable
                @change="changeOpeType"
              >
                <el-option
                  v-for="item in useDictionary('CheckOperateType')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="事务类型" label-width="70px">
              <el-select
                v-model="searchParam.effectTypeCode"
                placeholder="请选择事务类型"
                clearable
              >
                <el-option
                  v-for="item in effectTypeCodeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item> -->
            <el-form-item label="物料批次号" label-width="100px">
              <el-input
                v-model="searchParam.materialBatch"
                placeholder="请输入物料批次号"
                clearable
                @keyup.enter="search"
              />
            </el-form-item>
            <el-form-item label="检验项目名称" label-width="100px">
              <el-input
                v-model="searchParam.checkItemName"
                placeholder="请输入检验项目名称"
                clearable
                @keyup.enter="search"
              />
            </el-form-item>
            <el-form-item label="检验单号" label-width="100px">
              <el-input
                v-model="searchParam.effectCheckCode"
                placeholder="请输入检验单号"
                clearable
                @keyup.enter="search"
              />
            </el-form-item>
            <el-form-item label="产品名称" label-width="100px">
              <el-input
                v-model="searchParam.materialName"
                placeholder="请输入产品名称"
                clearable
                @keyup.enter="search"
              />
            </el-form-item>
            <!-- <el-form-item label="预检单号" label-width="70px">
              <el-input
                v-model="searchParam.effectPreCheckCode"
                placeholder="请输入预检单号"
                clearable
                @keyup.enter="search"
              />
            </el-form-item> -->
            <el-form-item>
              <el-button type="primary" @click="search"
                ><i-ep-search />搜索</el-button
              >
              <el-button @click="resetHandle"><i-ep-refresh />重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never" class="table-container">
          <el-table
            ref="singleTableRef"
            highlight-current-row
            v-loading="loading"
            :data="tableData"
            border
            @current-change="handleCurrentChange1"
          >
            <el-table-column
              label="检验单号"
              prop="effectCheckCode"
              min-width="150"
              show-overflow-tooltip
            >
              <template #default="scope">
                {{ scope.row.effectCheckCode ?? scope.row.orderNo }}
              </template>
            </el-table-column>
            <el-table-column
              label="物料批次号"
              prop="materialBatch"
              min-width="140"
              show-overflow-tooltip
              align="center"
            />
            <!-- <el-table-column
              label="事务类型"
              prop="effectTypeCode"
              min-width="100"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                {{ getEffectTypeCode(scope.row) }}
              </template>
            </el-table-column> -->
            <el-table-column
              label="检验项目名称"
              prop="checkItemName"
              min-width="180"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column
              label="产品"
              prop="materialName"
              min-width="140"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column
              label="项目"
              prop="projectName"
              min-width="100"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column
              label="工序"
              prop="processName"
              min-width="100"
              show-overflow-tooltip
              align="center"
            />
            <!-- <el-table-column
              label="预检单号"
              prop="effectPreCheckCode"
              min-width="150"
              show-overflow-tooltip
            />
            <el-table-column
              label="任务单号"
              prop="taskId"
              min-width="100"
              show-overflow-tooltip
            /> -->
            <el-table-column
              label="检验类型"
              prop="checkTypeName"
              min-width="150"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column
              label="检验结果"
              prop="checkResult"
              min-width="100"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                {{ useDictionary("CheckResult", scope.row.checkResult) }}
              </template>
            </el-table-column>
            <!-- <el-table-column
              label="生产时间"
              prop="productTime"
              min-width="150"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column
              label="班次"
              prop="classes"
              min-width="100"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column
              label="操作类型"
              prop="opeTypeCode"
              min-width="100"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                {{ useDictionary("CheckOperateType", scope.row.opeTypeCode) }}
              </template>
            </el-table-column> -->
            <el-table-column
              fixed="right"
              label="操作"
              width="120"
              align="center"
            >
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="openDialogdetail(scope.row)"
                  ><i-ep-search />
                  查看明细
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            :background="true"
            :current-page="pageable.pageNum"
            :page-size="pageable.pageSize"
            :page-sizes="[10, 25, 50, 100]"
            :total="pageable.total"
            layout="total, sizes, prev, pager, next, jumper"
            class="mt-[20px]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-card>

        <qmscheckdoc-edit
          :visible="addDialog.visible"
          :title="addDialog.title"
          :data="addDialog.data"
          :ruleData="addDialog.ruleData"
          @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
          :is-readonly="addDialog.readvisible"
          @change-visible="changeVisible"
        />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitBtn">确认</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { useRoute } from "vue-router";
import { checkCommon } from "@/views/qms/checkHook/checkCommon";

const route = useRoute();
defineOptions({
  name: "QMSQMSCHECKDOC",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  sopType: {
    type: String,
    default: "",
  },
  reportList: {
    type: Array,
    default: () => {
      return [];
    },
  },
});
// 请求参数
const requestApi = "/qms/qmspointcheckorder/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  effectCheckCode: "",
  sopTypeCode: props.sopType,
  materialBatch: "",
  checkItemName: "",
  materialName: "",
};

const deleteParam = {
  api: "/qms/qmspointcheckorder/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

const { effectTypeCodeList, getEffectTypeCode, changeOpeType, resetHandle } =
  checkCommon(searchParam, reset);
const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  ruleData: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/qms/qmspointcheckorder/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

const getRule = async (checkRuleId: string) => {
  const { data } = await request({
    url: `/qms/qmscheckrule/get/${checkRuleId}`,
    method: "get",
  });
  addDialog.ruleData = data;
};
// 查询详情
async function getStandard(id: string) {
  request({
    url: `/qms/qmspointcheckorder/getStandard/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}
/** 打开标准检验检验单表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "标准检验检验单详情";
  if (roleObj.checkRuleId !== null && roleObj.checkRuleId !== "")
    getRule(roleObj.checkRuleId);
  getStandard(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

const projectList = ref([]);

const getProjectList = async () => {
  const { data } = await request({
    url: "/mdm/mdmprojectinfo/getList",
    method: "post",
    data: {},
  });
  projectList.value = data;
};

const processList = ref([]);

const getProcessList = async () => {
  const { data } = await request({
    url: "/mdm/mdmprocess/getList",
    method: "post",
    data: {},
  });
  processList.value = data;
};

onMounted(() => {
  getProjectList();
  getProcessList();
  searchParam.value.effectPreCheckCode = route.query?.effectPreCheckCode;
  searchParam.value.sopTypeCode = props.sopType;
  getTableList();
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);
/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
}

// 点击确认
const submitBtn = () => {
  if (currentRow.value) {
    emit("change-visible", false, currentRow.value);
  } else {
    ElMessage.warning("请选择检验单");
  }
};

// 选择高亮
const singleTableRef = ref();
const currentRow = ref([]);
const handleCurrentChange1 = (val: any) => {
  currentRow.value = val;
  console.log(currentRow.value);
};

// 回显时设置选项
const breakSingleTableSelect = () => {
  //定义了一个空数组
  setChildrenSelection(tableData.value, props.reportList);
};

// 递归设置子节点的选中状态
const defaultCheckedKeys = ref([]);
function setChildrenSelection(node, selectedKeys) {
  node.forEach((item) => {
    selectedKeys.forEach((element) => {
      if (element.id == item.id) {
        nextTick(() => {
          //遍历回显数组
          //singleTableRef这个是在table上面加的ref的值  通过它的属性方法去看那几个属性打钩
          singleTableRef.value.toggleRowSelection(item, true); // 回显
        });
      }
    });
    if (item.nodes && item.nodes.length > 0) {
      setChildrenSelection(item.nodes, selectedKeys);
    }
  });
}
</script>
